import os
import time
import re
from datetime import datetime


class RebootPing:
    def __init__(self):
        self.start = True
        time.sleep(10)

    def exit_file(self):
        """
        Judge whether it exists file "ping_result.log"
        :return: True or False
        """
        # file_path = os.getcwd() + "ping_result.log"
        file_path = "/home/kylin/ping_result.log"
        result = os.path.exists(file_path)
        return result

    def parse_log(self):
        now_time = datetime.now().strftime("%Y-%m-%d %H:%M:S")
        print(now_time)
        with open("/home/kylin/ping_result.log", "r", encoding='utf8') as f:
            try:
                result = f.readlines()[13]
            except Exception as e:
                with open("/home/kylin/error.txt", 'a', encoding='utf8') as f:
                    f.write(now_time + "\t 未ping通，请查看ping_result.log是否有内容并检查网络 \t" + str(e) + "\n")
                    exit()
        try:
            num_result = \
            re.findall("(.*?) packets transmitted, (.*?) received, (.*?)% packet loss, time (.*?)ms", result)[
                0]
        except Exception as e2:
            with open("/home/kylin/error.txt", 'a', encoding='utf8') as f:
                f.write(now_time + "\t 未ping通，请查看ping_result.log是否有内容并检查网络 \t" + str(e2) + "\n")
                num_result = ""
                exit()

        with open("/home/kylin/result.txt", 'a', encoding='utf8') as f:
            f.write(result)
        print(result)

        if num_result[0] == num_result[1] and int(num_result[2]) == 0 and int(num_result[3]) < 15000:
            return True
        else:
            return False

    def ping_(self):
        os.popen("ping -c 10 www.baidu.com > /home/kylin/ping_result.log&")

    def main(self):
        if self.start == True:
            self.ping_()
            time.sleep(13)
            if self.exit_file():
                result = self.parse_log()
                return result


if __name__ == '__main__':
    ss = RebootPing()
    if ss.main() == True:
        os.popen("reboot")
